#include "global.h"

#include <QDir>
#include <qregularexpression.h>

Global::Global() {
    m_hashStr["OS"] = QSysInfo::productType();
    qDebug() <<"OS:" << getStr("OS");
    if(m_hashStr["OS"].compare("windows")==0){
        // m_hashStr["Serial-A"] = "COM14";
        // m_hashStr["Serial-B"] = "COM15";
        // m_hashStr["Serial-C"] = "COM17";
        // m_hashStr["Serial-D"] = "COM16";

        m_hashStr["Serial-A"] = "COM19";
        m_hashStr["Serial-B"] = "COM17";
        m_hashStr["Serial-C"] = "COM20";
        m_hashStr["Serial-D"] = "COM18";

        m_hashStr["Gpio-Dir"] = "C:/sys/class/gpio";
        QDir dir;
        dir.mkpath(m_hashStr["Gpio-Dir"]);
    }

    if(m_hashStr["OS"].compare("ubuntu") ==0){
        m_hashStr["Serial-A"] = "/dev/ttyACM0";
        m_hashStr["Serial-B"] = "/dev/ttyACM1";
        m_hashStr["Serial-C"] = "/dev/ttyACM2";
        m_hashStr["Serial-D"] = "/dev/ttyACM3";

        m_hashStr["Gpio-Dir"] = "/sys/class/gpio";
    }
}

Global &Global::instance()
{
    static QMutex mutex; // 互斥锁，保证多线程下创建唯一实例
    QMutexLocker locker(&mutex);
    static Global s_instance; // 静态局部变量，程序生命周期内唯一
    return s_instance;
}

void Global::add(const QString str, QObject *p)
{
    m_hashObj[str] = p;
}

QObject *Global::get(const QString str)
{
    return m_hashObj[str];
}

QString Global::getStr(const QString str)
{
    return m_hashStr[str];
}

int Global::strToSecond(const QString str)
{
    static QRegularExpression regex(R"((\d+)\s*([smhd]|min|sec|second|minute|hour|day))");

    QRegularExpressionMatch match = regex.match(str.toLower());
    if (!match.hasMatch()) {
        return -1; // 解析失败
    }

    int value = match.captured(1).toInt();
    QString unit = match.captured(2);

    if (unit == "s" || unit == "sec" || unit == "second") {
        return value; // 秒
    } else if (unit == "min" || unit == "m" || unit == "minute") {
        return value * 60; // 分钟转秒
    } else if (unit == "h" || unit == "hour") {
        return value * 3600; // 小时转秒
    } else if (unit == "d" || unit == "day") {
        return value * 86400; // 天转秒
    }

    return -1;
}
